# -*- coding: utf-8 -*-
import os
import re
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from apps import base_path
from apps.chart.visifire.utils import handleRequestURL

def buildin_params():
    params_list = ['datas', 'labels', 'type', 'size', 'title',
                   'alt', 'view3d']
    return set(params_list)


class ChartVisifire(webapp.RequestHandler):
    def _handleVisifire(self):
        custom_params = self.request.GET.keys()
#        判断参数是否是缺省参数的子集
        if set(custom_params) <= buildin_params():
            request_url = handleRequestURL(custom_params, self.request.query_string, dealwith='html')
            size = self.request.get("size")
            pattern = "^(\d{1,3})x(\d{1,3})$"
            match_obj = re.search(pattern, size)
            if size == "":
                size = [300, 500]
            elif re.search(pattern, size):
                size = size.split("x")
            else:
                return self.response.out.write("size format (%s) is not currect" % size)
            path = os.path.join(base_path, "templates/chart/visifire/visifire.html")
            t = template.render(path, {"request_url": "?%s" % request_url, "size": size})
            self.response.out.write(t)
        else:
            custom_params = [str(i) for i in custom_params]
            self.response.out.write("params in %s may not be currect" % custom_params)
    
    def _handleXml(self):
        custom_params = self.request.GET.keys()
#       接收参数、处理参数
        data = handleRequestURL(custom_params, self.request.query_string)
#        self.response.out.write(data)
        path = os.path.join(base_path, "templates/chart/visifire/xml/visifire.xml")
        t = template.render(path, data)
        self.response.headers['Content-Type'] = "text/xml"
        self.response.out.write(t)
    
    def get(self):
        if self.request.path.endswith('/chart/visifire/xml/'):
            self._handleXml()
        elif self.request.path.endswith('/chart/visifire/'):
            self._handleVisifire()
